import React, { Component, Fragment } from "react";
// antd
import { Dropdown, Table, Menu, Button, Col, Pagination, Form, Input, Select, Typography, Space, Tag, Tooltip, notification, message } from "antd";
import Action from "@c/buttonAction/Index";
import { DownOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';

// http
import http from '../../utils/request';
import {CopyToClipboard} from 'react-copy-to-clipboard';


// import XLSX from "xlsx"
import ExportJsonExcel from "js-export-excel";
import { cmdb_sheet_name, pagination_size_option } from "../../utils/common"


const { Text } = Typography;
const { Option } = Select;


class SlbListener extends Component {
    constructor(props){
        super(props)
        this.state = {
            loading: false,

            // 分页
            total: '',
            page: 1,
            page_number: 10,

            // 搜索
            search_instance_region: null,
            search_instance_platform: null,
            search_instance_account_name: null,
            search_instance_resource_type: null,
            search_instance_id: null,
            search_charge_type: null,
            search_alarm_status: null,
            search_option_account_name: [],
            search_option_platform: [],
            search_option_account: [],
            search_option_region: [],
            search_business: null,
            search_net_type: '公网',
            search_listener_type: '2',
            search_status: '非受信',

            // 业务线标签
            label_list_option_name: [],

            // 事业部标签
            label_division_list_option_name: '',

            selectedRowKeys: [],
            
            // 表格
            dataSource: [],
            columns: [
                {title: "实例ID/名称", dataIndex: "instance_id", key: "instance_id",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.instance_id} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.instance_id}</span></span>
                                </CopyToClipboard>
                                 
                                <Text >{rowData.name}</Text>
                            </Space>
                        )
                    }
                },
                {title: "云平台", dataIndex: "cloud-platform", key: "cloud-platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}-{rowData.account_name}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "业务线", dataIndex: "business", key: "business",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.business}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "地址", dataIndex: "address", key: "address",
                    render: (text, rowData) => {
                        return(
                            <span>{rowData.address}</span>
                        )
                    }
                },
                {title: "受信状态", dataIndex: "status", key: "status",
                    render: (text, rowData) => {
                        const status = rowData.status === '受信' ? <Tag color='green'>{rowData.status}</Tag> : <Tag color='red'>{rowData.status}</Tag>
                        return(
                            <span>{status}</span>
                        )
                    }
                },
                {title: "网络类型", dataIndex: "net_type", key: "net_type",
                    render: (text, rowData) => {
                        return(
                            <span>{rowData.net_type}</span>
                        )
                    }
                },
                {title: "监听信息", dataIndex: "pay_type", key: "pay_type",
                    render: (text, rowData) => {
                        return(
                            <div>{rowData.listener_protocol}/{rowData.listener_port}</div>
                        )
                    }
                },
                {title: "访问控制", dataIndex: "acl_status", key: "acl_status",
                    render: (text, rowData) => {
                        const acl_status = rowData.acl_status ? null : <Tag color='red'>禁用</Tag>
                        return(
                            <span>{acl_status}</span>
                        )
                    }
                },
                {title: "健康检查", dataIndex: "health_status", key: "health_status",
                    render: (text, rowData) => {
                        const health_status = rowData.health_status ? null : <Tag color='red'>禁用</Tag>
                        return(
                            <span>{health_status}</span>
                        )
                    }
                },
                {title: "描述信息", dataIndex: "description", key: "description"},
                {title: "主机列表", dataIndex: "server_list", key: "server_list", width: "100px", ellipsis: {showTitle: false,},
                    render: (text, rowData) => {
                        var tag_style = {margin: '2px'}
                        var server_list = rowData.server_list ? rowData.server_list : []
                        var server_data = []

                        server_list.map(acl => (
                            server_data.push(<div style={tag_style}>{acl}</div>)
                        ))

                        return(
                            <Tooltip placement="topLeft" title={server_data}>
                                {<div>{server_data}</div>}
                            </Tooltip>
                        )
                    }
                },
                {title: "控制规则", dataIndex: "acl_list", key: "acl_list", width: "100px", ellipsis: {showTitle: false, },
                    render: (text, rowData) => {
                        var tag_style = {margin: '2px', }
                        var acl_list = rowData.acl_list ? rowData.acl_list : []
                        var acl_data = []

                        acl_list.map(acl => (
                            acl_data.push(<Tag bordered={false} style={tag_style}>{acl.AclEntryIP}|{acl.AclEntryComment}</Tag>)
                        ))

                        return(
                            <Tooltip title={acl_data}>
                                {<span>{acl_data}</span>}
                            </Tooltip>
                        )
                    }
                },
                {title: "操作", dataIndex: "operation", key: "operation", fixed: 'right', 
                    render: (text, rowData) => {

                        return(
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditRenewalPriceBtn(rowData.instance_id)}>询价</Action.Button>
                                </Action>
                            </div>
                        )
                    }            
                }
            ],
        }
        this.formRefLabel = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
        this.loadDataBusiness()
        this.loadDataDivision()
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const search_option_platform = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_platform.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                search_option_platform: search_option_platform
            })
        })
    }

    loadDataBusiness = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/business', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const label_list_option = []
            const label_list_option_name = []
            for (let i = 0; i < resp_data.length; i++) {
                label_list_option.push(<Option key={resp_data[i].id}>{resp_data[i].name}</Option>)
                label_list_option_name.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            label_list_option_name.push(<Option key='none'>空标签</Option>)
            this.setState({
                label_list_option: label_list_option,
                label_list_option_name: label_list_option_name
            })
        })
    }

    loadDataDivision = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/division', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const label_division_list_option = []
            const label_division_list_option_name = []
            for (let i = 0; i < resp_data.length; i++) {
                label_division_list_option.push(<Option key={resp_data[i].id}>{resp_data[i].name}</Option>)
                label_division_list_option_name.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)

            }
            label_division_list_option_name.push(<Option key='none'>空标签</Option>)
            this.setState({
                label_division_list_option: label_division_list_option,
                label_division_list_option_name: label_division_list_option_name
            })
        })
    }


    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'instance_id': this.state.search_instance_id,
            'business': this.state.search_business,
            'division': this.state.search_division,
            'resource_type': this.state.search_instance_resource_type,
            'region': this.state.search_instance_region,
            'account_name': this.state.search_instance_account_name,
            'platform': this.state.search_instance_platform,
            'alarm_status': this.state.search_alarm_status,
            'net_type': this.state.search_net_type,
            'listener_type': this.state.search_listener_type,
            'status': this.state.search_status,
        }

        // 获取database列表
        http.get('/cloud/slb/listener', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    // 切换每页数量
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

     /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_instance_id: data.instance_id ? data.instance_id : null,
            search_instance_platform: data.platform ? data.platform : null,
            search_instance_account_name: data.account_name ? data.account_name : null,
            search_business: data.search_business,
            search_division: data.search_division,
            search_net_type: data.net_type ? data.net_type : null,
            search_listener_type: data.listener_type ? data.listener_type : null,
            search_status: data.status ? data.status : null,
            page: 1
        })
        this.loadData()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_instance_platform: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })
    

        } else {
            this.setState({
                search_option_account: '',
            })
        }
    }


    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_instance_account_name: value ? value : null
        })
    }

    // 搜索业务线
    onChangeBusiness = (value) => {
        this.setState({
            search_business: value ? value : null
        })
    }

    // 批量选中标签
    onSelectChange = (selectedRowKeys) => {
        this.setState({
            selectedRowKeys: selectedRowKeys
        })
    }

    // 一键导出
    onexportExcelBtn = () => {
        // 不同云产品添加自定义字段
        const _cmdb_sheet_filter = ['instance_id', 'name', 'platform', 'account_name', 'address', 'net_type', 'listener_protocol', 'listener_port', 'acl_status', 'health_status', 'description']
        const _cmdb_sheet_header = ['实例ID', '实例名称', '云平台', '云账户', '地址', '网络类型', '监听协议', '监听端口', '访问控制', '健康检查', '描述信息']

        let option = {}
        option.fileName = cmdb_sheet_name
        option.datas = [
            {
                sheetData: this.state.dataSource,
                sheetName: cmdb_sheet_name,
                sheetFilter: _cmdb_sheet_filter,
                sheetHeader: _cmdb_sheet_header
            }
        ]
        var toExcel = new ExportJsonExcel(option)
        toExcel.saveExcel()
    }

    // 修改受信状态
    onChangeStatusBtn = () => {
        this.setState({
            loading: true
        })
        if (this.state.selectedRowKeys.length>0) {
            const requestData = {
                instance_id_list: this.state.selectedRowKeys,
            }
            http.post('/cloud/slb/listener', requestData).then(response=>{
                message.success(response.data.msg)
                this.setState({
                    loading: false,
                    selectedRowKeys: []
                })
                this.loadData()
            })
        } else {
            message.info('请先选中需要添加受信的资源实例')
        }
    }

    render(){
        const { loading, columns, dataSource, page, total, search_option_platform, search_option_account, selectedRowKeys, label_list_option_name,
            label_division_list_option_name
        } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        }

        // <Button type="primary" onClick={() => this.onLabelBtn()} >批量打标签</Button>
        // <Button type="primary" onClick={this.onAddDatabaseBtn}>添加资产</Button>


        const operations = (
            <Menu
                items={[
                    {
                        label: (
                            <Action.Button onClick={() => this.onChangeStatusBtn()} >修改受信状态</Action.Button>
                        ),
                        key: '1',
                    },
                    {
                        label: (
                            <Action.Button onClick={() => this.onexportExcelBtn()} >导出页面数据</Action.Button>
                        ),
                        key: '2',
                    }
                ]}
            />
        );
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        var myStyleForm = {marginRight: '10px', marginTop: '5px'}

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch} size="small">
                    <Form.Item label="实例ID" name="instance_id" style={myStyleForm}>
                        <Input placeholder="实例ID"  />
                    </Form.Item>

                    <Form.Item label="云平台" name="platform" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择平台"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_platform}
                        </Select>
                    </Form.Item>   

                    <Form.Item label="云账户" name="account_name" style={myStyleForm}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: 200 }}
                                placeholder="请选择云账户"
                                onChange={this.onChangeAccountName}
                                >
                                {search_option_account}
                            </Select>                      
                    </Form.Item>

                    <Form.Item label="业务线搜索" name="search_business" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangeBusiness}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_list_option_name}
                        </Select>
                    </Form.Item>

                    <Form.Item label="事业部搜索" name="search_division" size="small" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择事业部"
                            optionFilterProp="children"
                            onChange={this.onChangeDivision}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_division_list_option_name}
                        </Select>
                    </Form.Item>

                    <Form.Item label="网络类型" name="net_type" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="网络类型"
                            >
                            <Option key="内网">内网</Option>
                            <Option key="公网">公网</Option>
                        </Select>                      
                    </Form.Item>

                    <Form.Item label="端口类型" name="listener_type" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="网络类型"
                            >
                            <Option key="1">WEB</Option>
                            <Option key="2">OTHER</Option>
                            <Option key="">ALL</Option>
                        </Select>      
                    </Form.Item>

                    <Form.Item label="受信状态" name="status" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="受信状态"
                            >
                            <Option key="受信">受信</Option>
                            <Option key="非受信">非受信</Option>
                            <Option key="">ALL</Option>
                        </Select>      
                    </Form.Item>
    
                    <Form.Item shouldUpdate={true} style={myStyleForm}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle1}>
                    <Dropdown overlay={operations}>
                        <Action.Button>
                            <Space>
                                更多操作
                                <DownOutlined />
                            </Space>
                        </Action.Button>
                    </Dropdown>
                </div>

                <Table
                    // size="small"
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 600, x: 2000 }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            pageSizeOptions={pagination_size_option}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

            </Fragment>
        )
    }
}

export default SlbListener;